package com.galudisu.ddd

import akka.actor._
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import akka.stream.scaladsl._

class Server(boot: Bootstrap, service: String) {

  import akka.http.scaladsl.server.Directives._

  implicit val system = ActorSystem()
  implicit val mater = ActorMaterializer()

  import system.dispatcher


  //Boot up each service module from the config and get the routes
  val routes = boot.bootup(system).map(_.routes)
  val definedRoutes = routes.reduce(_ ~ _)

  val finalRoutes = pathPrefix("api")(definedRoutes)

  val serviceConf = system.settings.config.getConfig(service)

  val serverSource =
    Http().bind(interface = serviceConf.getString("ip"), port = serviceConf.getInt("port"))


  val log = Logging(system.eventStream, "Server")

  log.info("Starting up on port {} and ip {}", serviceConf.getString("port"), serviceConf.getString("ip"))

  val sink = Sink.foreach[Http.IncomingConnection](_.handleWith(finalRoutes))

  serverSource.to(sink).run
}
